<template>
  <div ref="mapContainer" v-loading="mapSet.loading" class="map-container" />
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance } from "vue";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet.markercluster/dist/MarkerCluster.css";
import "leaflet.markercluster/dist/MarkerCluster.Default.css";
import MarkerClusterGroup from "leaflet.markercluster";
import { deviceDetection } from "@pureadmin/utils";
import { mapJson } from "@/api/mock";
import car from "@/assets/car.png";

const mapContainer = ref(null);
const map = ref(null);
const markerCluster = ref(null);
const mapSet = reactive({
  loading: deviceDetection() ? false : true
});
const instance = getCurrentInstance();

// 定义props
const props = defineProps({
  center: {
    type: Array,
    default: () => [39.90923, 116.397428]
  },
  zoom: {
    type: Number,
    default: 13
  }
});

onMounted(() => {
  initMap();
});

onUnmounted(() => {
  if (map.value) {
    map.value.remove();
  }
});

const initMap = () => {
  // 初始化地图
  map.value = L.map(mapContainer.value).setView(props.center, props.zoom);

  // 添加高德地图图层
  L.tileLayer(
    "https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
    {
      subdomains: "1234",
      attribution: "© 高德地图"
    }
  ).addTo(map.value);

  // 添加地图控件
  L.control.zoom({ position: "topright" }).addTo(map.value);
  L.control.layers(null, null, { position: "topright" }).addTo(map.value);

  // 初始化标记聚合
  markerCluster.value = new MarkerClusterGroup({
    showCoverageOnHover: false,
    maxClusterRadius: 80
  }).addTo(map.value);

  // 加载车辆数据
  loadVehicleData();
};

const loadVehicleData = () => {
  mapJson()
    .then(({ data }) => {
      data.forEach(item => {
        addVehicleMarker(item);
      });
      mapSet.loading = false;
    })
    .catch(err => {
      console.log("err:", err);
      mapSet.loading = false;
    });
};

const addVehicleMarker = vehicle => {
  const { lng, lat, driver, plateNumber, orientation } = vehicle;
  const icon = L.divIcon({
    html: `<img style="transform: rotate(${360 - Number(orientation)}deg);" src="${car}" />`,
    className: "custom-marker",
    iconSize: [36, 36],
    iconAnchor: [18, 18]
  });

  const marker = L.marker([lat, lng], { icon }).addTo(markerCluster.value);

  marker.bindTooltip(`<div>${plateNumber}(${driver})</div>`, {
    direction: "bottom",
    offset: [0, 5],
    permanent: true,
    className: "vehicle-tooltip"
  });

  marker.on("click", () => {
    map.value.setView([lat, lng], 13);
  });
};

// 封装对外暴露的方法
defineExpose({
  setCenter: latlng => {
    map.value.setView(latlng);
  },
  addMarker: (latlng, popupContent) => {
    const marker = L.marker(latlng).addTo(map.value);
    if (popupContent) marker.bindPopup(popupContent);
    return marker;
  }
});
</script>

<style scoped>
.map-container {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: calc(100vh - 86px);
}

:deep(.custom-marker) {
  img {
    width: 36px;
    height: 36px;
    object-fit: contain;
  }
}

:deep(.vehicle-tooltip) {
  background: transparent;
  border: none;
  box-shadow: none;
  font-size: 14px;
  font-weight: 500;
}
</style>
